package com.zbkj.crmeb.order.channel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.plat.by.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.crmeb.core.common.CommonResult;
import com.utils.RestTemplateUtil;
import com.crmeb.core.config.RestTemplateConfig;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.LavitaOrderRequest;
import com.zbkj.crmeb.order.request.LavitaOrderRequest.OrderInfo;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreProductAttrResult;
import com.zbkj.crmeb.store.service.StoreProductAttrResultService;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;
import com.zbkj.crmeb.user.service.UserService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class LavitaStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    StoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    UserService userService;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    /********* lavita配置参数  *********/
    @Value("${lavita.appid}")
    private String lavitaAppid;
    @Value("${lavita.appsecret}")
    private String lavitaAppsecret;
    @Value("${lavita.url.domain}")
    private String lavitaDomian;
    @Value("${lavita.url.order}")
    private String lavitaOrder;

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        try {
            // 组建订单对象
            LavitaOrderRequest lavitaOrderRequest = new LavitaOrderRequest();
            lavitaOrderRequest.setToken(DigestUtil.md5Hex("appid=" + lavitaAppid + "&appsecret=" + lavitaAppsecret + "&times=" + DateUtil.format(new Date(), "YYYY-MM-dd")));//订单号
            if(9 != storeOrder.getSource()) {
                storeOrder.setPushOrderNo(orderInfoVoList.get(0).getChildOrderNumber());
            }
            lavitaOrderRequest.setOrderId(storeOrder.getPushOrderNo());//订单号
            BigDecimal cost = new BigDecimal("0");
            lavitaOrderRequest.setCouponPay("0");//优惠券抵扣0元
            lavitaOrderRequest.setFreightPay(storeOrder.getFreightPrice().toString());//运费
            lavitaOrderRequest.setFreightPayType("0");//快递,自提
            lavitaOrderRequest.setConsignee(storeOrder.getRealName());//收件人姓名
            lavitaOrderRequest.setPhone(storeOrder.getUserPhone());//收件人手机号
            lavitaOrderRequest.setProvincial(storeOrder.getProvince());//省
            lavitaOrderRequest.setCity(storeOrder.getCity());//市
            lavitaOrderRequest.setArea(storeOrder.getDistrict());//区
            lavitaOrderRequest.setAddress(storeOrder.getDetail());//详细地址
            List<OrderInfo> list = new ArrayList<>();
            for (StoreOrderInfoVo order : orderInfoVoList) {
                String sourceSkuId = order.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
                StoreProductAttrResult storeProductAttrResult = storeProductAttrResultService.getByProductId(order.getProductId());
                List<JSONObject> jsonResult = JSONObject.parseArray(storeProductAttrResult.getResult(), JSONObject.class);
                String skuCode = null;
                String price = null;
                if (ObjectUtils.isNotEmpty(jsonResult)) {
                    for (JSONObject result : jsonResult) {
                        if (sourceSkuId.equals(result.getString("sourceSkuId"))) {
                            skuCode = result.getString("skuCode");
                            price = result.getString("sourcePrice");
                            cost = cost.add(new BigDecimal(price));
                        }
                    }
                }
                if (sourceSkuId.startsWith(ProductTypeEnum.LAVITA.getCode() + "-")) {
                    sourceSkuId = sourceSkuId.replaceFirst(ProductTypeEnum.LAVITA.getCode() + "-", "");
                }
                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setProductId(Integer.valueOf(sourceSkuId));
                orderInfo.setSkuCode(skuCode);
                orderInfo.setQty(order.getInfo().getCartNum().toString());
                orderInfo.setPrice(price);//源拉取的价格,港币
                list.add(orderInfo);
            }
            lavitaOrderRequest.setProductList(list);//订单商品
            lavitaOrderRequest.setTotalPay(cost.toString());//整单支付金额未扣除优惠券,包含邮费的金额
            Result result = pushOrder(storeOrder, lavitaOrderRequest, orderInfoVoList);
            if(!result.isSuccess()){
                return CommonResult.success(result.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.success();
    }


    /**
     * 获取lavita商品数据和详情
     *
     * @param @param  id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return BuyerProductResDTO
     * @throws
     * @Description:
     * @author songjc
     */
    private Result pushOrder(StoreOrder storeOrder, LavitaOrderRequest request, List<StoreOrderInfoVo> orderInfoList) {
        // 组装请求url
        StringBuilder url = new StringBuilder();
        url.append(lavitaDomian);
        url.append(lavitaOrder);
        url.append("?appid=");
        url.append(lavitaAppid);
        // 发送请求
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        HttpEntity<String> formEntity = new HttpEntity(JSON.toJSONString(request), headers);
        ResponseEntity<String> response = restTemplate.exchange(url.toString(), HttpMethod.POST, formEntity, String.class);
        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");

            log.info("--------------- {} ---------------", errorMessage);
            return new Result(false, null, errorMessage);
        }
        JSONObject responseData = JSONObject.parseObject(response.getBody());
        String code = responseData.getString("code");
        if ("1".equals(code)) {
            JSONObject jsonObject = responseData.getJSONObject("data");
            String serno = jsonObject.getString("Serno");

            //新增采购单
            storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.LAVITA.getCode());
            //新增采购商品
            storeOrderFactory.insertPurchaseGoods(orderInfoList, storeOrder, true, "成功", serno, false);
            if (storeOrder.getPushStatus() != 2) {
        		StoreOrder storeOrderUpdate = new StoreOrder();
        		storeOrderUpdate.setId(storeOrder.getId());
        		storeOrderUpdate.setPushStatus(1);
        		storeOrderUpdate.setPushMessage(responseData.toJSONString());
                storeOrderDao.updateById(storeOrderUpdate);
            }
            return new Result(true, null, responseData.toJSONString());
        } else {
            //新增采购单
        	storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.LAVITA.getCode());
            //新增采购商品
        	storeOrderFactory.insertPurchaseGoods(orderInfoList, storeOrder, false, "失败", null, false);
    		StoreOrder storeOrderUpdate = new StoreOrder();
    		storeOrderUpdate.setId(storeOrder.getId());
    		storeOrderUpdate.setPushStatus(2);
    		storeOrderUpdate.setPushMessage(responseData.toJSONString());
            storeOrderDao.updateById(storeOrderUpdate);
            return new Result(false, null, responseData.toJSONString());
        }
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }

}
